package com.xiaogao.security.aspect;

import com.xiaogao.security.annotation.HasPerm;
import com.xiaogao.common.exception.BusinessException;
import com.xiaogao.common.utils.token.JwtUtils;
import com.xiaogao.common.utils.RedisUtils;
import com.xiaogao.sys.response.SysPermResponse;
import com.xiaogao.sys.service.SysPermService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 权限校验的切面
 */
@Aspect
@Component
@Slf4j
public class HasPermAspect {
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SysPermService sysPermService;


    // 检测HasPerm注解的
    @Pointcut("@annotation(com.xiaogao.common.annotation.HasPerm)")
    public void hasPermPointcut() {
    }

    @Before("hasPermPointcut() && @annotation(hasPerm)")  // 在执行方法前进行权限校验
    public void hasPerm(HasPerm hasPerm) {
        log.info("进入hasPerm切面------------------");
        String perm = hasPerm.value();
        String token = request.getHeader("token");
        String userId = JwtUtils.userId(token);
        List<SysPermResponse> sysPermResponseList = sysPermService.queryByUserId(userId);
        if (sysPermResponseList.isEmpty()) {
            throw new BusinessException(401, "没有权限进行此操作！");
        }
        List<String> buttonPerms = sysPermResponseList.stream().filter(x -> x.getType().equals("3")).map(SysPermResponse::getPerm).toList();
        if (!buttonPerms.contains(perm)) {
            throw new BusinessException(401, "没有权限进行此操作！");
        }
    }
}
